

#import "RequestUrlBook.h"

//static RequestUrlBook* gRequestUrlBook = nil;

@implementation RequestUrlBook
@synthesize nameUrlFmtDict = _nameUrlFmtDict;
@synthesize nameUrlDict = _nameUrlDict;
@synthesize hostDict = _hostDict;
@synthesize currentHost = _currentHost;
@synthesize responseDict = _responseDict;

+ (NSString*)findUrlConfigPath
{
    return [[NSBundle mainBundle] pathForResource:@"protocolconfig" ofType:@"plist"];
}

+ (NSString*)findHostConfigPath
{
    return [[NSBundle mainBundle] pathForResource:@"hostconfig" ofType:@"plist"];
}

- (id)initWithConfigFile
{
    self = [super init];
    if(self)
    {
        //读取环境host配置
        NSString* hostConfigPath = [RequestUrlBook findHostConfigPath];
        self.hostDict = [NSMutableDictionary dictionaryWithContentsOfFile:hostConfigPath];
        
        //从文件读取
        NSString* configpath = [RequestUrlBook findUrlConfigPath];
        NSDictionary* dict = [NSDictionary dictionaryWithContentsOfFile:configpath];
        
        self.nameUrlFmtDict = [NSMutableDictionary dictionaryWithCapacity:[dict count]];
        self.nameUrlDict = [NSMutableDictionary dictionaryWithCapacity:[dict count]];
        self.responseDict = [NSMutableDictionary dictionaryWithCapacity:[dict count]];
        
        NSEnumerator* keyEnum = [dict keyEnumerator];
        NSString* key;
        while(key = [keyEnum nextObject])
        {
            NSDictionary* d = [dict objectForKey:key];
            NSString* v = [d objectForKey:@"url"];
            NSString* resp = [d objectForKey:@"response"];
            [self.nameUrlFmtDict setObject:v forKey:key];
            [self.responseDict setObject:resp forKey:key];
        }

        NSString* curHost = [_hostDict objectForKey:@"host"];
        
        [self setHost:curHost];
    }
    return self;
}

-(void)setHost:(NSString*)hostKey
{
    NSString* hostValue = [_hostDict objectForKey:hostKey];
    if (hostValue)
    {
        NSDictionary* dict = _nameUrlFmtDict;
        NSEnumerator* keyEnum = [dict keyEnumerator];
        NSString* key;
        while(key = [keyEnum nextObject])
        {
            NSString* v = [dict objectForKey:key];
            v = [NSString stringWithFormat:v,hostValue];
            [self.nameUrlDict setObject:v forKey:key];
        }
        
        [_currentHost release];
        _currentHost = [hostValue retain];
    }
}

-(void)dealloc
{
    self.nameUrlDict = nil;
    [super dealloc];
}

- (NSString*)getRequestUrlByName:(NSString*)name
{
    return @"http://www.easytoo.net:8180/CTSAppSrv/cts";
    //return @"http://219.136.254.114:8180/CTSAppSrv/cts";//[self.nameUrlDict objectForKey:name];
}

- (NSString*)getResponseByName:(NSString*)name
{
    return [self.responseDict objectForKey:name];
}


@end
